"use client"

import { useState, useEffect, useCallback } from "react"
import { ChevronRight, ChevronDown, File, Folder, FolderOpen, TerminalIcon, Zap, Play, Save, RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"
import { useToast } from "@/hooks/use-toast"
import { useWebContainer } from "@/hooks/use-webcontainer"
import dynamic from 'next/dynamic'

// 动态导入 Monaco Editor 以避免 SSR 问题
const MonacoEditor = dynamic(() => import('@monaco-editor/react'), {
  ssr: false,
  loading: () => <div className="flex items-center justify-center h-full text-gray-400">Loading editor...</div>
})

interface FileNode {
  name: string
  type: "file" | "folder"
  children?: FileNode[]
  isOpen?: boolean
  path: string
}

const initialFileStructure: FileNode[] = [
  { name: "index.html", type: "file", path: "index.html" },
  { name: "main.js", type: "file", path: "main.js" },
  { name: "style.css", type: "file", path: "style.css" },
  { name: "package.json", type: "file", path: "package.json" },
]

export default function VSCodeInterface() {
  const [files, setFiles] = useState<FileNode[]>(initialFileStructure)
  const [selectedFile, setSelectedFile] = useState<string | null>("index.html")
  const [activeTab, setActiveTab] = useState("code")
  const [fileContents, setFileContents] = useState<Record<string, string>>({})
  const [isProjectInitialized, setIsProjectInitialized] = useState(false)
  const { toast } = useToast()

  const {
    webcontainer,
    isLoading,
    error,
    terminalOutput,
    previewUrl,
    writeFile,
    readFile,
    initializeProject,
    installDependencies,
    startDevServer,
    clearTerminal,
    clearError
  } = useWebContainer()

  // 初始化项目
  useEffect(() => {
    if (webcontainer && !isProjectInitialized) {
      const init = async () => {
        await initializeProject()
        
        // 读取初始文件内容
        const contents: Record<string, string> = {}
        for (const file of initialFileStructure) {
          if (file.type === "file") {
            const content = await readFile(file.path)
            if (content) {
              contents[file.path] = content
            }
          }
        }
        setFileContents(contents)
        setIsProjectInitialized(true)
        
        toast({
          title: "项目初始化成功",
          description: "WebContainer 已准备就绪，可以开始编码了！"
        })
      }
      
      init()
    }
  }, [webcontainer, isProjectInitialized, initializeProject, readFile, toast])

  // 保存文件
  const saveFile = useCallback(async (path: string, content: string) => {
    if (!webcontainer) return
    
    try {
      await writeFile(path, content)
      setFileContents(prev => ({ ...prev, [path]: content }))
      toast({
        title: "文件已保存",
        description: `${path} 保存成功`
      })
    } catch (err) {
      toast({
        title: "保存失败",
        description: err instanceof Error ? err.message : "未知错误",
        variant: "destructive"
      })
    }
  }, [webcontainer, writeFile, toast])

  // 运行项目
  const runProject = useCallback(async () => {
    if (!webcontainer || !isProjectInitialized) return
    
    try {
      clearTerminal()
      toast({
        title: "正在启动项目",
        description: "安装依赖并启动开发服务器..."
      })
      
      await installDependencies()
      await startDevServer()
      
      toast({
        title: "项目启动成功",
        description: "开发服务器已启动，请查看预览窗口"
      })
    } catch (err) {
      toast({
        title: "启动失败",
        description: err instanceof Error ? err.message : "未知错误",
        variant: "destructive"
      })
    }
  }, [webcontainer, isProjectInitialized, clearTerminal, installDependencies, startDevServer, toast])

  const toggleFolder = (index: number) => {
    const newFiles = [...files]
    if (newFiles[index].type === "folder") {
      newFiles[index].isOpen = !newFiles[index].isOpen
    }
    setFiles(newFiles)
  }

  const FileIcon = ({ node }: { node: FileNode }) => {
    if (node.type === "folder") {
      return node.isOpen ? (
        <FolderOpen className="w-4 h-4 text-blue-400" />
      ) : (
        <Folder className="w-4 h-4 text-blue-400" />
      )
    }
    return <File className="w-4 h-4 text-gray-400" />
  }

  const FileTreeItem = ({ node, index, depth = 0 }: { node: FileNode; index: number; depth?: number }) => (
    <div key={node.name}>
      <div
        className={`flex items-center gap-1 px-2 py-1 hover:bg-gray-700 cursor-pointer text-sm ${
          selectedFile === node.path ? "bg-gray-600" : ""
        }`}
        style={{ paddingLeft: `${8 + depth * 16}px` }}
        onClick={() => {
          if (node.type === "folder") {
            toggleFolder(index)
          } else {
            setSelectedFile(node.path)
          }
        }}
      >
        {node.type === "folder" && (
          <div className="w-4 h-4 flex items-center justify-center">
            {node.isOpen ? (
              <ChevronDown className="w-3 h-3 text-gray-400" />
            ) : (
              <ChevronRight className="w-3 h-3 text-gray-400" />
            )}
          </div>
        )}
        {node.type === "file" && <div className="w-4" />}
        <FileIcon node={node} />
        <span className="text-gray-200">{node.name}</span>
      </div>
      {node.type === "folder" && node.isOpen && node.children && (
        <div>
          {node.children.map((child, childIndex) => (
            <FileTreeItem key={child.name} node={child} index={childIndex} depth={depth + 1} />
          ))}
        </div>
      )}
    </div>
  )

  const getLanguageFromPath = (path: string): string => {
    const ext = path.split('.').pop()
    switch (ext) {
      case 'js': return 'javascript'
      case 'ts': return 'typescript'
      case 'html': return 'html'
      case 'css': return 'css'
      case 'json': return 'json'
      default: return 'plaintext'
    }
  }

  // 清理终端输出文本
  const cleanTerminalText = (text: string): string => {
    // 更全面的 ANSI 转义序列清理
    return text
      // 移除 ANSI 颜色和样式代码
      .replace(/\x1b\[[0-9;]*[mGKHF]/g, '')
      // 移除 ANSI 光标控制序列
      .replace(/\x1b\[[0-9;]*[ABCD]/g, '')
      // 移除其他 ANSI 转义序列
      .replace(/\x1b\[[?]?[0-9;]*[hlr]/g, '')
      // 移除 ANSI OSC 序列 (Operating System Command)
      .replace(/\x1b\][0-9;]*;[^\x07]*\x07/g, '')
      // 移除回车符，只保留换行符
      .replace(/\r\n/g, '\n')
      .replace(/\r/g, '')
      // 移除退格符
      .replace(/\x08/g, '')
      // 移除其他控制字符，但保留换行符和制表符
      .replace(/[\x00-\x08\x0B-\x1F\x7F]/g, '')
  }

  // 格式化终端输出
  const formatTerminalOutput = (outputs: string[]): string[] => {
    const formatted: string[] = []
    let currentLine = ''
    
    for (const output of outputs) {
      const cleaned = cleanTerminalText(output)
      
      // 按换行符分割，但保持连续性
      const chunks = cleaned.split('\n')
      
      for (let i = 0; i < chunks.length; i++) {
        const chunk = chunks[i]
        
        if (i === 0) {
          // 第一个块追加到当前行
          currentLine += chunk
        } else {
          // 遇到换行符，保存当前行并开始新行
          if (currentLine.trim() || currentLine.length > 0) {
            formatted.push(currentLine)
          }
          currentLine = chunk
        }
      }
    }
    
    // 添加最后一行（如果有内容）
    if (currentLine.trim() || currentLine.length > 0) {
      formatted.push(currentLine)
    }
    
    // 过滤掉只包含重复字符的行（可能是进度条残留）
    return formatted.filter(line => {
      const trimmed = line.trim()
      if (!trimmed) return false
      
      // 检查是否是重复字符组成的行（如进度条）
      const uniqueChars = new Set(trimmed.split(''))
      if (uniqueChars.size === 1 && trimmed.length > 10) {
        return false
      }
      
      // 过滤掉只包含特殊字符的行
      if (/^[\[\](){}<>|\\\/\-_=+*&^%$#@!~`'".,;:?\s]*$/.test(trimmed)) {
        return false
      }
      
      return true
    })
  }

  return (
    <div className="h-screen bg-gray-900 text-white flex flex-col">
      {/* Top Tabs */}
      <div className="flex items-center bg-gray-800 border-b border-gray-700">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="bg-transparent border-none h-10 p-0">
            <TabsTrigger
              value="code"
              className="bg-transparent border-none text-gray-300 data-[state=active]:text-blue-400 data-[state=active]:bg-gray-700 rounded-none px-4 py-2"
            >
              Code
            </TabsTrigger>
            <TabsTrigger
              value="preview"
              className="bg-transparent border-none text-gray-300 data-[state=active]:text-blue-400 data-[state=active]:bg-gray-700 rounded-none px-4 py-2"
            >
              Preview
            </TabsTrigger>
          </TabsList>
        </Tabs>
        
        {/* Toolbar */}
        <div className="flex items-center gap-2 px-4">
          <Button
            size="sm"
            variant="ghost"
            onClick={() => selectedFile && saveFile(selectedFile, fileContents[selectedFile] || '')}
            disabled={!selectedFile || isLoading}
            className="text-gray-300 hover:text-white"
          >
            <Save className="w-4 h-4 mr-1" />
            保存
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={runProject}
            disabled={!isProjectInitialized || isLoading}
            className="text-green-400 hover:text-green-300"
          >
            <Play className="w-4 h-4 mr-1" />
            运行
          </Button>
          {isLoading && (
            <RefreshCw className="w-4 h-4 text-blue-400 animate-spin" />
          )}
        </div>
      </div>

      {/* Main Content Area with Resizable Terminal */}
      <ResizablePanelGroup direction="vertical" className="flex-1">
        {/* Main Content Panel */}
        <ResizablePanel defaultSize={75} minSize={30}>
          <div className="flex h-full overflow-hidden">
            {/* Sidebar */}
            <div className="w-64 bg-gray-800 border-r border-gray-700 flex flex-col">
              {/* Sidebar Header */}
              <div className="p-3 border-b border-gray-700">
                <div className="flex items-center gap-2 text-sm font-medium text-gray-300">
                  <span>Files</span>
                  <span className="ml-auto text-xs text-gray-500">Search</span>
                </div>
              </div>

              {/* File Tree */}
              <ScrollArea className="flex-1">
                <div className="py-2">
                  {files.map((node, index) => (
                    <FileTreeItem key={node.name} node={node} index={index} />
                  ))}
                </div>
              </ScrollArea>
            </div>

            {/* Editor Area */}
            <div className="flex-1 flex flex-col">
              <Tabs value={activeTab} className="flex-1 flex flex-col">
                <TabsContent value="code" className="flex-1 m-0">
                  <div className="h-full bg-gray-900 relative">
                    {selectedFile ? (
                      <div className="h-full flex flex-col">
                        {/* File Tab */}
                        <div className="bg-gray-800 border-b border-gray-700 px-4 py-2">
                          <span className="text-sm text-gray-300">{selectedFile}</span>
                        </div>
                        
                        {/* Monaco Editor */}
                        <div className="flex-1">
                          <MonacoEditor
                            height="100%"
                            language={getLanguageFromPath(selectedFile)}
                            theme="vs-dark"
                            value={fileContents[selectedFile] || ''}
                            onChange={(value) => {
                              if (value !== undefined && selectedFile) {
                                setFileContents(prev => ({ ...prev, [selectedFile]: value }))
                              }
                            }}
                            options={{
                              minimap: { enabled: false },
                              fontSize: 14,
                              lineNumbers: 'on',
                              roundedSelection: false,
                              scrollBeyondLastLine: false,
                              automaticLayout: true,
                              tabSize: 2,
                              insertSpaces: true,
                              wordWrap: 'on',
                              contextmenu: true,
                              selectOnLineNumbers: true,
                              glyphMargin: false,
                              folding: true,
                              lineDecorationsWidth: 10,
                              lineNumbersMinChars: 3,
                            }}
                          />
                        </div>
                      </div>
                    ) : (
                      <div className="h-full flex items-center justify-center text-gray-500">
                        <div className="text-center">
                          <File className="w-16 h-16 mx-auto mb-4 text-gray-600" />
                          <p>选择一个文件开始编辑</p>
                        </div>
                      </div>
                    )}
                  </div>
                </TabsContent>
                
                <TabsContent value="preview" className="flex-1 m-0">
                  <div className="h-full bg-white relative">
                    {previewUrl ? (
                      <iframe
                        src={previewUrl}
                        className="w-full h-full border-none"
                        title="Preview"
                      />
                    ) : (
                      <div className="h-full flex items-center justify-center text-gray-600">
                        <div className="text-center">
                          <Play className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                          <p>点击"运行"按钮启动项目预览</p>
                          {!isProjectInitialized && (
                            <p className="text-sm text-gray-500 mt-2">正在初始化项目...</p>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </TabsContent>
              </Tabs>
            </div>
          </div>
        </ResizablePanel>

        {/* Resizable Handle */}
        <ResizableHandle withHandle />

        {/* Terminal Panel */}
        <ResizablePanel defaultSize={25} minSize={15} maxSize={60}>
          <div className="h-full bg-gray-900 border-t border-gray-700 flex flex-col">
            {/* Terminal Tabs */}
            <div className="flex items-center bg-gray-800 px-4 py-2 border-b border-gray-700">
              <div className="flex items-center gap-4">
                <Button variant="ghost" size="sm" className="text-gray-300 hover:text-white p-1 bg-gray-700">
                  <TerminalIcon className="w-4 h-4 mr-1" />
                  Terminal
                </Button>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  className="text-gray-500 hover:text-gray-300 p-1"
                  onClick={clearTerminal}
                >
                  清除
                </Button>
              </div>
              
              {error && (
                <div className="ml-auto flex items-center gap-2">
                  <span className="text-red-400 text-sm">{error}</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={clearError}
                    className="text-red-400 hover:text-red-300 p-1"
                  >
                    ✕
                  </Button>
                </div>
              )}
            </div>

            {/* Terminal Content */}
            <ScrollArea className="flex-1">
              <div className="p-4 font-mono text-sm">
                <div className="text-green-400 mb-2">
                  ~/project $ WebContainer Online IDE
                </div>
                
                {terminalOutput.length > 0 ? (
                  <div className="space-y-1">
                    {formatTerminalOutput(terminalOutput).map((line, index) => (
                      <div key={index} className="text-gray-300 whitespace-pre-wrap break-words">
                        {line}
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-gray-500">
                    {isLoading ? '正在初始化 WebContainer...' : '终端准备就绪。点击"运行"开始项目。'}
                  </div>
                )}
                
                {previewUrl && (
                  <div className="mt-4 p-2 bg-green-900/20 border border-green-700 rounded">
                    <div className="text-green-400 text-sm">
                      🚀 服务器已启动: <a href={previewUrl} target="_blank" rel="noopener noreferrer" className="underline hover:text-green-300">{previewUrl}</a>
                    </div>
                  </div>
                )}
              </div>
            </ScrollArea>
          </div>
        </ResizablePanel>
      </ResizablePanelGroup>
    </div>
  )
}
